$(function () {
  var $window = $(window);
  var $container = $('.container');
  var $header = $('.meizu-header');
  var siteHeaderHeight = $header.outerHeight();
  var $productSub = $('#meizu-header-sub');
  var $subnav = $('.subnav');
  var $backToTop = $('.toTop');
  var topOld = $(window).scrollTop();
  var topNew = 0;
  var scrollLeft = 0;
  var headerHeight = $('#meizu-header').height();
  var subnavHeight = $subnav.outerHeight();
  var subnavTop = $subnav.offset() ? $subnav.offset().top : 0;


  window.isIE = function() {
    if (!!window.ActiveXObject || "ActiveXObject" in window || /MSIE ([^;]+)/.test(navigator.userAgent))
      return true;
    else
      return false;
  }

  window.isMac = function () {
    return navigator.platform.indexOf('Mac') !== -1;
  };

  window.isMobile = function () {
    return !!navigator.userAgent.match(/android|webos|ip(hone|ad|od)|opera (mini|mobi|tablet)|iemobile|windows.+(phone|touch)|mobile|fennec|kindle (Fire)|Silk|maemo|blackberry|playbook|bb10\; (touch|kbd)|Symbian(OS)|Ubuntu Touch/i);
  };

  window.isRetina = function () {
    var mediaQuery = '(-webkit-min-device-pixel-ratio: 1.5), (min--moz-device-pixel-ratio: 1.5), (-o-min-device-pixel-ratio: 3/2), (min-resolution: 1.5dppx)';
    if (window.devicePixelRatio > 1) {
      return true;
    }
    if (window.matchMedia && window.matchMedia(mediaQuery).matches) {
      return true;
    }
    return false;
  };

  // 识别mac和ie
  if (isMac()) {
    $('body').addClass('mac');
  }
  if(isIE()) {
    $('body').addClass('ie');
  } else {
    $('body').addClass('notIE');
  }

  window.Cookie = {
    set: function(key, val, h) {
      if (h) {
        var date = new Date();
        date.setTime(date.getTime() + (h * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
      } else {
        var expires = '';
      }
      document.cookie = key + "=" + val + expires + "; domain=.meizu.com;path=/";
    },
    get: function(key) {
      var n = key + '=';
      var ca = document.cookie.split(';');
      for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
          c = c.substring(1, c.length);
        }
        if (c.indexOf(n) == 0) {
          return c.substring(n.length, c.length);
        }
      }
      return null;
    },
    remove: function(key) {
      this.set(key, '', -1);
    }
  }

  var img = $('img[data-src]');
  // img标签的src，做视网膜兼容
  if (isRetina()) {
    img.each(function () {
      var src = $(this).attr('data-src-2x');
      $(this).attr('src', src);
    });
  } else {
    img.each(function () {
      var src = $(this).attr('data-src');
      $(this).attr('src', src);
    });
  }

  // 获取视口尺寸
  window.getViewport = function() {
    if(document.compatMode == 'BackCompat') {
      return {
        width: document.body.clientWidth,
        height: document.body.clientHeight
      }
    } else {
      return {
        width: document.documentElement.clientWidth,
        height: document.documentElement.clientHeight
      }
    }
  }


  // 二级导航菜单展开
  if(!Cookie.get('subnavShow')) {
      Cookie.set('subnavShow', '1', 240);
      toggleSubnavMenu();
      setTimeout(toggleSubnavMenu, 2000);
  }
  $('.subnav-disclosure').on('click', function () {
    toggleSubnavMenu();
  })
  setTimeout(function () {
    $window.scroll(function () {
      if($subnav.hasClass('open')) {
        toggleSubnavMenu();
      }
    })
  }, 2000);
  function toggleSubnavMenu () {
    $subnav.toggleClass('open');
    $('.subnav-menu').slideToggle(200, function () {
      subnavHeight = $subnav.outerHeight();
    });
  }
  window.toggleSubnavMenu = toggleSubnavMenu;
  
  // 二级导航菜单是否fixed，需要的话就在每个页面调用该方法，如果需要随滚动方向进行收展，请传一个参数，值为1就好
  window.fixSubnav = function(type) {
    var subnavAnimEnd = true; // 是否动画完成
    $window.scroll(function () {
      topNew = $window.scrollTop();
      scrollLeft = $window.scrollLeft();
      if (topNew > subnavTop) {
        $subnav.addClass('fixed').css('left', -scrollLeft);
      } else {
        $subnav.removeClass('fixed').css('left', 0);
      }

      // fixed 且会随滚动收展
      if(type === 1) {

        // 向下滚动(收起)
        if(topNew > topOld) {
          if(topNew > subnavTop + subnavHeight) {
            if(subnavAnimEnd == true) {
              subnavAnimEnd = false;
              $subnav.animate({top: -subnavHeight}, 200, 'linear', function() {subnavAnimEnd = true;});
            }
          } else if (topNew > subnavTop && topNew < subnavTop + subnavHeight) {
            $subnav.stop().css({top: 0});
            subnavAnimEnd = true;
          }
        }
        // 向上滚动(展开)
        else {

          if (topNew > subnavTop) {
            if(subnavAnimEnd == true) {
              subnavAnimEnd = false;
              $subnav.animate({top: 0}, 200,'linear', function() {subnavAnimEnd = true;});
            }
          } else if(topOld > subnavTop) {
            $subnav.stop().css({top: subnavTop});
            subnavAnimEnd = true;
          }
        }
      }
      topOld = topNew;
    });
  };

  // 视频播放器
  window.Player = function (options) {

      this.videoWidth = options.videoWidth?options.videoWidth:960;
      this.videoHeight = options.videoHeight?options.videoHeight:540;
      this.playerWrapId = options.playerWrapId?options.playerWrapId:'player1';

      this.$playerWrap = $('#'+this.playerWrapId);
      this.$player = $(".jp-jplayer", this.$playerWrap);
      this.$jpMask = $(".jp-mask", this.$playerWrap);

      var _this = this;
      this.$player.jPlayer({
        ready: function () {
          _setMedia(_this.$playerWrap.attr('data-video'));
        },
        cssSelectorAncestor: '#'+_this.playerWrapId,
        swfPath: "http://www2.res.meizu.com/zh_cn/videos",
        supplied: "webmv, flv, m4v",
        size: {
          width: _this.videoWidth+'px',
          height: _this.videoHeight+'px'
        },
        useStateClassSkin: true,
        autoBlur: true,
        smoothPlayBar: true,
        volume: 0.5,
        keyEnabled: true,
        keyBindings: {
          play: {
            key: 32, // space
            fn: function(f) {
              if(f.status.paused) {
                f.play();
              } else {
                f.pause();
              }
            }
          },
          esc: {
            key: 27, // esc
            fn: function(f) {
              _this.$jpMask.click();
            }
          }
        }
      });

      function _setMedia (videoUrl) {
        _this.$player.jPlayer("setMedia", {
            m4v: videoUrl+".mp4",
            flv: videoUrl+".flv",
            webmv: videoUrl+".webm"
        });
      }

      this.init();
      return this;

  }
  Player.prototype.init = function () {
    var _this = this;
    var timer1;
    this.$jpInterface = $('.jp-interface', _this.$playerWrap);
    $('.jp-wrapper', _this.$playerWrap).mousemove(function () {
      clearTimeout(timer1);
      _this.$jpInterface.show();
    }).mouseout(function () {
      _this.$jpInterface.hide();
    });
    this.$jpMask.click(function () {
      _this.hideAndPause();
    })
  }
  Player.prototype.showAndPlay = function () {
      var _this = this;
      var $body = $('body');
      var $window = $(window);
      var scrollHeight = $body[0].scrollHeight;
      var scrollTop = $window.scrollTop();
      var clientHeight = $body.height();

      scrollTop = $window.scrollTop();

      $('body').addClass('vh');
      $(".jp-mask, .jp_container", _this.$playerWrap).show();
      this.$jpMask.height(scrollHeight).css({top: scrollTop});
      $(".jp_container", _this.$playerWrap).css({width: _this.videoWidth, top: scrollTop + (clientHeight - _this.videoHeight)/2});

      _this.$jpInterface.focus();
      setTimeout(function () {
        _this.$player.jPlayer('play');
      }, 200)

      setTimeout(function () {
        _this.$jpInterface.hide();
      }, 1000);
  }
  Player.prototype.hideAndPause = function () {
    var _this = this;
      $('body').removeClass('vh');
      $(".jp-mask, .jp_container",  _this.$playerWrap).hide();
      _this.$player.jPlayer('pause');
  }


  // 进入页面时候，先隐藏网站头部
  window.hideSiteHeader = function () {
    // 这里必须做一点延时才能生效，why? I don't know~
    setTimeout(function() {
      document.getElementsByTagName('body')[0].scrollTop = siteHeaderHeight;
    }, 50)
  }

  $window.scroll(function () {
    topNew = $window.scrollTop();
    if (topNew < 900) {
      $backToTop.fadeOut();
    } else {
      $backToTop.fadeIn();
    }
  })
  // 当浏览器宽度变小的时候，保持界面宽度
  .resize(function() {
    if (getViewport().width < 1080) {
      $container.addClass('JSWrapperWidth');
      $subnav.addClass('JSWrapperWidth');
      $header.addClass('JSWrapperWidth');
      $productSub.css('width', '1080px');
    } else {
      $container.removeClass('JSWrapperWidth');
      $subnav.removeClass('JSWrapperWidth');
      $header.removeClass('JSWrapperWidth');
      $productSub.css('width', '100%');
    }
  });

  // 返回顶部
  $backToTop.click(function () {
    $('html,body').animate({scrollTop: 0}, 500);
  });


  $window.scroll().resize();

})